<?php

namespace app\home\controller\login;

use app\BaseController;
use app\common\model\HomeTokenModel;
use app\common\model\UserModel as models;
use app\common\traites\PublicCrudTrait;
use app\validate\home\Login as validates;
use \captcha\Captcha;
use think\exception\ValidateException;
use think\facade\Db;

class Login extends BaseController
{
    protected $model;
    use PublicCrudTrait;

    /**
     * 登陆
     */
    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //获取列表信息 登陆
    public function index()
    {
        //过滤数据
        $postField = 'phone,pwd';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('login')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([], config('ToConfig.http_code.error'), $e->getError());
        }

        $find = $this->model->where(['user_name|phone' => $post['phone'], 'pwd' => pwdEncryption($post['pwd'])])->find();
        if (empty($find)) return show([], config('ToConfig.http_code.error'), '账号或者密码错误');
        $find = $find->toArray();
        if ($find['status'] != 1) return show([], config('ToConfig.http_code.error'), '网络连接错误');

        $find['token'] = $token = home_api_token($find['id']);

        $HomeTokenModel = new HomeTokenModel();
        //查询是否存在这条token的用户
        $update = $HomeTokenModel->where('user_id', $find['id'])
            ->update(['token' => $token, 'create_time' => date('Y-m-d H:i:s')]);

        //数据不存在时插入
        if ($update == 0) {
            $HomeTokenModel->insert([
                'token' => $token, 'user_id' => $find['id'], 'create_time' => date('Y-m-d H:i:s')
            ]);
        }

        //登陆成功后存入 session
        session('home_user', $find);
        (new \app\common\service\LoginLog())->login(2);//登陆日志
        return show($find);
    }

    //注册
    public function register()
    {
        //过滤数据
        $postField = 'user_name,phone,pwd,codes,nickname,captcha';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('register')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([], config('ToConfig.http_code.error'), $e->getError());
        }

        if (!(new Captcha())->check($post['captcha'])) show([], config('ToConfig.http_code.error'), '验证码不正确');

        $find = $this->model->where('phone|user_name', $post['phone'])->find();
        if ($find) return show([], config('ToConfig.http_code.error'), '该手机号已存在');

        $data = [
            'phone' => $post['phone'],
            'nickname' => isset($post['phone']) ? $post['phone'] : 'game' . rand(1000, 9999),
            'user_name' => $post['phone'],
            'pwd' => pwdEncryption($post['pwd']),
            'create_time' => date('Y-m-d H:i:s'),
            'invitation_code' => generateCode(),
            'type' => 2,
            'withdraw_pwd' => home_tx_pwd(),
        ];

        //推广用户查询 //查询推广代理商
        if (isset($post['codes']) && !empty($post['codes'])) {
            if (preg_match('/[a-zA-Z]/', $post['codes'])) {
                //可以输入 codes
                $agent = $this->model->where('invitation_code', $post['codes'])->find();
            } else {
                //也可输入对方id
                $agent = $this->model->where('id', $post['codes'])->find();
            }
            if ($agent) {
                $data['agent_id'] = $agent->id;
            }
        }
        //用户注册的时候写入  洗码率
        // 启动事务
        $save = false;
        Db::startTrans();
        try {
            $this->model->save($data);
            Db::name('dianji_user_set')->insert(['u_id' => $this->model->id, 'xima_lv' => get_config('app_user_xima')['value']]);
            // 提交事务
            $save = true;
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return show([], 0, $e->getMessage());
        }
        //插入数据

        if (!$save) return show([], config('ToConfig.http_code.error'), '注册失败');
        return show();
    }



    //试用用户登陆
    public function on_trial_user_login(): string
    {
        $rand = userkey(rand(8, 15));//生成账号
        $phone = rand(20000000000, 30000000000);
        $data = [
            'money_balance'=>2000,
            'phone' => $phone,
            'nickname' => 'test' . rand(1000, 9999),
            'user_name' => $phone,
            'pwd' => pwdEncryption(123456),
            'create_time' => date('Y-m-d H:i:s'),
            'invitation_code' => $rand,
            'type' => 2,
            'is_fictitious'=>1,
            'withdraw_pwd' => home_tx_pwd(),
        ];

        //用户注册的时候写入  洗码率
        // 启动事务
        Db::startTrans();
        try {
            $this->model->save($data);
            $data['id'] = $this->model->id;
            Db::name('dianji_user_set')->insert(['u_id' => $data['id'], 'xima_lv' => get_config('app_user_xima')['value']]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return show([], 0, $e->getMessage());
        }

        $data['token'] = home_api_token($data['id']);
        $HomeTokenModel = new HomeTokenModel();
        $HomeTokenModel->insert([
            'token' => $data['token'], 'user_id' => $data['id'], 'create_time' => date('Y-m-d H:i:s')
        ]);
        session('home_user', $data);
        return show($data);
    }


    //验证码
    public function verify()
    {
        return (new Captcha())->conf(0)->create();
    }

    //退出
    public function sign_out()
    {
        session('home_user', '');
        return show();
    }


}